package day03;

import com.blackhorse.domain.Account;
import com.blackhorse.domain.AccountUser;
import com.blackhorse.domain.QueryVo;
import com.blackhorse.domain.User;
import com.blackhorse.xml.dao.AccountMapper;
import com.blackhorse.xml.dao.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Demo1_OneToOne {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private UserMapper userMapperr;
    private AccountMapper accountMapper;

    @Before
    public void init() {
        try {
            InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = builder.build(in);
            sqlSession = sqlSessionFactory.openSession();
            userMapperr = sqlSession.getMapper(UserMapper.class);
            accountMapper = sqlSession.getMapper(AccountMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void destory() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    @Test
    public void testFindAll() {
        List<Account> accounts = accountMapper.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    //查询所有账户，同时一对一关联查询用户（使用编写子类方式，使用较少）
    @Test
    public void testFindAllAccount() {
        List<AccountUser> aus = accountMapper.findAllAccount();
        for (AccountUser au : aus) {
            System.out.println(au);
        }
    }

    //查询所有账户，同时一对一关联查询用户（使用Account包装User对象方式）
    @Test
    public void testFindAllAccountWithUser() {
        List<Account> accounts = accountMapper.findAllAccountWithUser();
        for (Account account : accounts) {
            System.out.println("---------------------------------------");
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }
}
